import Vue from "vue";
import Router from "vue-router";
import NProgress from '@/utils/nprogress'
import { getToken } from '@/utils/cookies'
import store from '@/store/index'

Vue.use(Router)

const whiteList = ['/login']

const router = new Router({
	mode: 'hash',
	routes: [
		{
			path: '/login',
			component: {
				render(h) {
					return h('h3', { style: 'text-align: center;' }, 'Login')
				}
			}
		}
	]
})



const initDynamicRouter = () => {
	return new Promise((resolve, reject) => {
		store
			.dispatch('GenerateRoutes')
			.then(() => {
				router.addRoutes(store.getters.addRouters)
				resolve()
			})
			.catch(() => {
				Message.error('请求用户信息失败，请重试')
				reject()
			})
	})
}

router.beforeEach(async (to, from, next) => {
	NProgress.start()
	/* has token */
	if (getToken()) {
		if (to.path.toLocaleLowerCase() === '/login') {
			if (getToken()) return next(from.fullPath)
			resetRouter()
			return next()
		}
		if (!store.getters.addRouters.length) {
			await initDynamicRouter()
			return next({ ...to, replace: true })
		}
		next()
	} else {
		if (whiteList.includes(to.path)) {
			next()
		} else {
      next({ path: '/login', replace: true })
			NProgress.done()
		}
	}
})

router.afterEach(() => {
	NProgress.done() // finish progress bar
})

const resetRouter = () => {
}

export default router